<template>
  <view class="complete-container">
    <!-- 顶部导航 -->
    <view class="nav-header">
      <text class="nav-back" @click="goBack">返回</text>
      <text class="nav-title">完成工单</text>
    </view>

    <!-- 工单信息 -->
    <view class="workorder-info">
      <view class="info-item">
        <text class="info-label">工单类型：</text>
        <text class="info-value">{{ workorderData.repairType }}</text>
      </view>
      <view class="info-item">
        <text class="info-label">房产信息：</text>
        <text class="info-value">{{ workorderData.jzxm }} - {{ workorderData.htbh }}</text>
      </view>
      <view class="info-item">
        <text class="info-label">报修内容：</text>
        <text class="info-value">{{ workorderData.repairContent }}</text>
      </view>
    </view>

    <!-- 表单区域 -->
    <view class="form-section">
      <view class="form-item">
        <text class="form-label">处理结果</text>
        <uni-easyinput
          v-model="formData.log"
          type="textarea"
          placeholder="请输入处理结果和说明"
          :clearable="true"
          :maxlength="500"
        />
      </view>

      <view class="form-item">
        <text class="form-label">现场照片</text>
        <view class="upload-section">
          <view class="upload-btn" @click="chooseImage">
            <text class="upload-icon">+</text>
            <text class="upload-text">添加照片</text>
          </view>
          <view class="image-list" v-if="formData.images.length > 0">
            <view 
              class="image-item" 
              v-for="(image, index) in formData.images" 
              :key="index"
            >
              <image :src="image.path || image.url" class="preview-image" mode="aspectFill" />
              <text class="delete-btn" @click="deleteImage(index)">×</text>
            </view>
          </view>
        </view>
      </view>

                <view class="form-item">
            <text class="form-label">位置信息</text>
            <view class="location-section">
              <view class="location-info">
                <text class="location-text">{{ locationText }}</text>
                <text class="location-btn" @click="getLocation">获取位置</text>
              </view>
              <view class="coordinates" v-if="formData.latitude && formData.longitude">
                <text class="coord-text">纬度: {{ formData.latitude }}</text>
                <text class="coord-text">经度: {{ formData.longitude }}</text>
              </view>
              <view class="manual-input" v-if="showManualInput">
                <uni-easyinput
                  v-model="manualLatitude"
                  placeholder="请输入纬度"
                  type="number"
                />
                <uni-easyinput
                  v-model="manualLongitude"
                  placeholder="请输入经度"
                  type="number"
                />
                <button class="confirm-btn" @click="confirmManualLocation">确认</button>
              </view>
              <view class="manual-toggle">
                <text class="toggle-text" @click="toggleManualInput">
                  {{ showManualInput ? '隐藏手动输入' : '手动输入坐标' }}
                </text>
              </view>
            </view>
          </view>
      
      <!-- GUID修改选项 -->
      <view class="form-item">
        <view class="guid-option">
          <text class="form-label">是否需要修改GUID码</text>
          <switch 
            :checked="needChangeGuid" 
            @change="onGuidSwitchChange"
            color="#007AFF"
          />
        </view>
      </view>
      
      <!-- GUID修改表单 -->
      <view class="guid-form" v-if="needChangeGuid">
        <view class="form-item">
          <text class="form-label">原GUID码</text>
          <view class="old-guid-display">
            <text class="guid-text">{{ workorderData.jguid || '无' }}</text>
          </view>
        </view>
        
        <view class="form-item">
          <text class="form-label">新GUID码</text>
          <uni-easyinput
            v-model="formData.newGuid"
            placeholder="请输入新的GUID码"
            :clearable="true"
          />
        </view>
        
        <view class="form-item">
          <text class="form-label">更换原因</text>
          <uni-easyinput
            v-model="formData.changeReason"
            type="textarea"
            placeholder="请输入GUID码更换原因"
            :clearable="true"
            :maxlength="200"
            :autoHeight="true"
          />
        </view>
      </view>
    </view>

    <!-- 提交按钮 -->
    <view class="submit-section">
      <button class="submit-btn" @click="submitComplete" :disabled="submitting">
        {{ submitting ? '提交中...' : '提交完成' }}
      </button>
    </view>
  </view>
</template>

<script>
import { completeRepair, uploadRepairImage } from '@/api/door/repair'
import config from '@/config'
import { getToken } from '@/utils/auth'
import request from '@/utils/request'

export default {
  data() {
    return {
      workorderId: '',
      workorderData: {},
      formData: {
        log: '',
        images: [],
        latitude: '',
        longitude: '',
        newGuid: '', // 新增的GUID码
        changeReason: '' // 新增的更换原因
      },
      locationText: '点击获取位置信息',
      submitting: false,
      showManualInput: false,
      manualLatitude: '',
      manualLongitude: '',
      needChangeGuid: false // 新增的GUID修改开关
    }
  },
  onLoad(options) {
    if (options.id) {
      this.workorderId = options.id
    }
    if (options.workorderData) {
      try {
        this.workorderData = JSON.parse(decodeURIComponent(options.workorderData))
        console.log('工单数据:', this.workorderData)
      } catch (error) {
        console.error('解析工单数据失败:', error)
        this.$modal.msgError('工单数据解析失败')
      }
    }
  },
  methods: {
    goBack() {
      uni.navigateBack()
    },

    // 选择图片
    async chooseImage() {
      try {
        const res = await new Promise((resolve, reject) => {
          uni.chooseImage({
            count: 9 - this.formData.images.length,
            sizeType: ['compressed'],
            sourceType: ['camera', 'album'],
            success: resolve,
            fail: reject
          })
        })
        
        console.log('选择图片成功:', res)
        console.log('图片路径:', res.tempFilePaths)
        
        // 立即上传选中的图片
        for (let filePath of res.tempFilePaths) {
          try {
            const uploadResult = await uploadRepairImage({
              filePath: filePath
            })
            
            if (uploadResult.code === 200) {
              // 将上传成功的图片信息添加到表单中
              const imageInfo = {
                name: uploadResult.originalFilename || 'image.jpg',
                url: uploadResult.url,
                fileName: uploadResult.fileName,
                path: filePath // 保留本地路径用于显示
              }
              this.formData.images.push(imageInfo)
              console.log('图片上传成功:', uploadResult)
            } else {
              uni.showToast({
                title: '图片上传失败',
                icon: 'none'
              })
            }
          } catch (error) {
            console.error('图片上传失败:', error)
            uni.showToast({
              title: '图片上传失败',
              icon: 'none'
            })
          }
        }
        
        console.log('当前图片列表:', this.formData.images)
      } catch (error) {
        console.error('选择图片失败:', error)
        this.$modal.msgError('选择图片失败')
      }
    },

    // 删除图片
    deleteImage(index) {
      this.formData.images.splice(index, 1)
    },

    // 获取位置
    async getLocation() {
      console.log('开始获取位置...')
      this.$modal.loading('正在获取位置...')
      try {
        const res = await new Promise((resolve, reject) => {
          console.log('调用uni.getLocation...')
          uni.getLocation({
            type: 'gcj02',
            success: (result) => {
              console.log('位置获取成功回调:', result)
              resolve(result)
            },
            fail: (error) => {
              console.log('位置获取失败回调:', error)
              reject(error)
            }
          })
        })
        
        this.$modal.closeLoading()
        console.log('获取位置成功:', res)
        this.formData.latitude = res.latitude.toString()
        this.formData.longitude = res.longitude.toString()
        this.locationText = '位置获取成功'
        
        // 获取地址信息
        this.getAddressInfo(res.latitude, res.longitude)
      } catch (error) {
        this.$modal.closeLoading()
        console.error('获取位置失败:', error)
        console.log('尝试备用位置获取方法...')
        this.getLocationFallback()
      }
    },

    // 获取地址信息
    getAddressInfo(latitude, longitude) {
      // 这里可以调用地图API获取详细地址
      // 暂时使用坐标显示
      this.locationText = `位置: ${latitude.toFixed(6)}, ${longitude.toFixed(6)}`
    },

    // 备用位置获取方法
    getLocationFallback() {
      console.log('使用备用位置获取方法...')
      // 尝试使用不同的参数
      uni.getLocation({
        type: 'wgs84',
        success: (res) => {
          console.log('备用方法获取位置成功:', res)
          this.formData.latitude = res.latitude.toString()
          this.formData.longitude = res.longitude.toString()
          this.locationText = '位置获取成功'
          this.getAddressInfo(res.latitude, res.longitude)
        },
        fail: (error) => {
          console.error('备用方法也失败:', error)
          this.$modal.msgError('无法获取位置，请手动输入或检查定位权限')
        }
      })
    },

    // 切换手动输入
    toggleManualInput() {
      this.showManualInput = !this.showManualInput
    },

    // 确认手动输入的位置
    confirmManualLocation() {
      if (!this.manualLatitude || !this.manualLongitude) {
        this.$modal.msgError('请输入完整的坐标信息')
        return
      }

      const lat = parseFloat(this.manualLatitude)
      const lng = parseFloat(this.manualLongitude)

      if (isNaN(lat) || isNaN(lng)) {
        this.$modal.msgError('请输入有效的坐标数值')
        return
      }

      this.formData.latitude = lat.toString()
      this.formData.longitude = lng.toString()
      this.locationText = '手动输入位置'
      this.showManualInput = false
      this.manualLatitude = ''
      this.manualLongitude = ''
      
      this.$modal.msgSuccess('位置信息已保存')
    },

    // GUID修改开关变化
    onGuidSwitchChange(e) {
      this.needChangeGuid = e.detail.value
      if (!this.needChangeGuid) {
        this.formData.newGuid = ''
        this.formData.changeReason = ''
      }
    },


    // 提交完成
    async submitComplete() {
      // 验证表单
      if (!this.formData.log || !this.formData.log.trim()) {
        this.$modal.msgError('请输入处理结果')
        return
      }

      if (!this.formData.latitude || !this.formData.longitude) {
        this.$modal.msgError('请获取位置信息')
        return
      }

      if (this.needChangeGuid && (!this.formData.newGuid || !this.formData.newGuid.trim())) {
        this.$modal.msgError('请输入新的GUID码')
        return
      }

      if (this.needChangeGuid && (!this.formData.changeReason || !this.formData.changeReason.trim())) {
        this.$modal.msgError('请输入GUID码更换原因')
        return
      }

      this.submitting = true
      this.$modal.loading('正在提交...')

      try {
        // 提取已上传图片的fileName
        let imgUrls = []
        if (this.formData.images.length > 0) {
          console.log('处理已上传的图片，共', this.formData.images.length, '张')
          imgUrls = this.formData.images.map(image => image.fileName).filter(Boolean)
          console.log('提取的图片fileName:', imgUrls)
        }

        const params = {
          repairOrderId: parseInt(this.workorderId),
          log: this.formData.log.trim(),
          latitude: this.formData.latitude,
          longitude: this.formData.longitude,
          img: imgUrls.join(',') // 多张图片用逗号分隔
        }

        console.log('提交完成工单参数:', params)
        const response = await completeRepair(params)

        if (response.code === 200) {
          // 如果需要修改GUID，调用GUID修改接口
          if (this.needChangeGuid) {
            console.log('开始修改GUID码...')
            try {
              const guidParams = {
                id: this.workorderData.adslId, // 使用工单数据中的adslId
                xguid: this.formData.newGuid.trim(),
                reason: this.formData.changeReason.trim()
              }
              console.log('GUID修改参数:', guidParams)
              
              const guidResponse = await request({
                url: '/door/adsl/changeGuid',
                method: 'post',
                data: guidParams
              })
              
              if (guidResponse.code === 200) {
                console.log('GUID修改成功')
                this.$modal.closeLoading()
                this.$modal.msgSuccess('工单完成并成功修改GUID码')
              } else {
                console.error('GUID修改失败:', guidResponse.msg)
                this.$modal.closeLoading()
                this.$modal.msgError(`工单已完成，但GUID修改失败: ${guidResponse.msg}`)
              }
            } catch (guidError) {
              console.error('GUID修改接口调用失败:', guidError)
              this.$modal.closeLoading()
              this.$modal.msgError('工单已完成，但GUID修改失败，请稍后重试')
            }
          } else {
          this.$modal.closeLoading()
          this.$modal.msgSuccess('提交成功')
          }
          
          // 返回上一页并刷新
          setTimeout(() => {
            uni.navigateBack({
              success: () => {
                // 通知上一页刷新数据
                const pages = getCurrentPages()
                const prevPage = pages[pages.length - 2]
                if (prevPage && prevPage.refreshData) {
                  prevPage.refreshData()
                }
              }
            })
          }, 1500)
        } else {
          this.$modal.closeLoading()
          this.$modal.msgError(response.msg || '提交失败')
        }
      } catch (error) {
        this.$modal.closeLoading()
        console.error('提交完成工单失败:', error)
        this.$modal.msgError('网络异常，请稍后重试')
      } finally {
        this.submitting = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.complete-container {
  background-color: #f5f6f7;
  min-height: 100vh;
}

.nav-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  
  .nav-back {
    color: #007AFF;
    font-size: 28rpx;
  }
  
  .nav-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }
}

.workorder-info {
  background-color: #fff;
  margin: 20rpx;
  padding: 30rpx;
  border-radius: 16rpx;
  
  .info-item {
    display: flex;
    margin-bottom: 20rpx;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .info-label {
      font-size: 26rpx;
      color: #666;
      width: 140rpx;
    }
    
    .info-value {
      font-size: 26rpx;
      color: #333;
      flex: 1;
    }
  }
}

.form-section {
  background-color: #fff;
  margin: 20rpx;
  padding: 30rpx;
  border-radius: 16rpx;
  
  .form-item {
    margin-bottom: 30rpx;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .form-label {
      font-size: 28rpx;
      color: #333;
      margin-bottom: 15rpx;
      display: block;
    }
  }
}

.upload-section {
  .upload-btn {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 200rpx;
    height: 200rpx;
    border: 2rpx dashed #ddd;
    border-radius: 8rpx;
    background-color: #f8f9fa;
    
    .upload-icon {
      font-size: 60rpx;
      color: #999;
      margin-bottom: 10rpx;
    }
    
    .upload-text {
      font-size: 24rpx;
      color: #999;
    }
  }
  
  .image-list {
    display: flex;
    flex-wrap: wrap;
    gap: 20rpx;
    margin-top: 20rpx;
    
    .image-item {
      position: relative;
      width: 200rpx;
      height: 200rpx;
      
      .preview-image {
        width: 100%;
        height: 100%;
        border-radius: 8rpx;
      }
      
      .delete-btn {
        position: absolute;
        top: -10rpx;
        right: -10rpx;
        width: 40rpx;
        height: 40rpx;
        background-color: #ff4d4f;
        color: #fff;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 24rpx;
      }
    }
  }
}

.location-section {
  .location-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx;
    background-color: #f8f9fa;
    border-radius: 8rpx;
    border: 1px solid #e9ecef;
    
    .location-text {
      font-size: 26rpx;
      color: #333;
    }
    
    .location-btn {
      font-size: 24rpx;
      color: #007AFF;
      padding: 10rpx 20rpx;
      border: 1px solid #007AFF;
      border-radius: 20rpx;
    }
  }
  
  .coordinates {
    margin-top: 15rpx;
    
    .coord-text {
      display: block;
      font-size: 24rpx;
      color: #666;
      margin-bottom: 5rpx;
    }
  }
  
  .manual-input {
    margin-top: 20rpx;
    padding: 20rpx;
    background-color: #f8f9fa;
    border-radius: 8rpx;
    border: 1px solid #e9ecef;
    
    .confirm-btn {
      margin-top: 15rpx;
      width: 100%;
      height: 60rpx;
      background-color: #007AFF;
      color: #fff;
      border-radius: 30rpx;
      font-size: 28rpx;
      border: none;
    }
  }
  
  .manual-toggle {
    margin-top: 15rpx;
    text-align: center;
    
    .toggle-text {
      font-size: 24rpx;
      color: #007AFF;
      text-decoration: underline;
    }
  }
}

.guid-option {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx;
  background-color: #f8f9fa;
  border-radius: 8rpx;
  border: 1px solid #e9ecef;

  .form-label {
    font-size: 26rpx;
    color: #333;
  }
}

.guid-form {
  margin-top: 20rpx;
  padding: 20rpx;
  background-color: #f8f9fa;
  border-radius: 8rpx;
  border: 1px solid #e9ecef;

  .old-guid-display {
    margin-top: 15rpx;
    padding: 10rpx;
    background-color: #fff;
    border-radius: 8rpx;
    border: 1px solid #e9ecef;

    .guid-text {
      font-size: 24rpx;
      color: #333;
    }
  }
}

.submit-section {
  padding: 30rpx;
  
  .submit-btn {
    width: 100%;
    height: 80rpx;
    background-color: #007AFF;
    color: #fff;
    border-radius: 40rpx;
    font-size: 32rpx;
    font-weight: bold;
    border: none;
    
    &:disabled {
      background-color: #ccc;
    }
  }
}
</style> 